/*
 * 会员信息
 */
define(function(require, exports, module) {
    var ELView = require("elview");
    var Subnav = require("subnav");
    var Dialog = require("dialog");
    var Grid = require("grid");
    var Form = require("form");
    var aw = require("ajaxwrapper");
    var store = require("store");
    var activeUser = store.get("user");
    var enmu = require("enums");
    require("jquery/jquery-qrcode/jquery.qrcode.min");
    var VerForm = require("form-2.0.0");
    var VerDialog = require("dialog-1.0.0");

    var template = require("./member.tpl");
    require("./member.css");

    var count = 0;
    var isGovern = false;
    var pktemp = [];
    //获取文件后缀名
    //输入"abc.jpg" 输出".jpg"
    function getFileExt(str) {
        var result = /\.[^\.]+$/.exec(str);
        return result;
    }

    function isIdCardNo(num) {
        num = num.toUpperCase();
        //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X。
        if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
            return false;
        }
    }
    var detailFetchProperties = "pkMember," +
        "dataSource," +
        "memberTypes.pkMemberType," +
        "memberTypes.name," +
        "organization.pkOrganization," +
        "organization.name," +
        "personalInfo.name," +
        "personalInfo.sex.*," +
        "personalInfo.birthday," +
        "personalInfo.lunarBirthday," +
        "personalInfo.idType.*," +
        "personalInfo.idNumber," +
        "personalInfo.electronicMail," +
        "personalInfo.cultureLevel.*," +
        "memberNumber," +
        "personalInfo.phone," +
        "personalInfo.mobilePhone," +
        "personalInfo.maritalStatus," +
        "personalInfo.work," +
        "personalInfo.position," +
        "personalInfo.zipCode," +
        "personalInfo.qq," +
        "personalInfo.weChat," +
        "personalInfo.nativePlace.*," +
        "personalInfo.houseRegisterDetail," +
        
        "personalInfo.address," +
        "personalInfo.areaAddress," +
        "personalInfo.areaAddress.fullName," +
        
        "personalInfo.nationlity," +
        "personalInfo.version," +
        "personalInfo.pkPersonalInfo," +
        "status.*," +
        "deleteFlag.*," +
        "sosPhone1," +
        "sosPhone2," +
        "version," +
        "description," +
        "personalInfo.contactAddresses.pkContactAddress," +
        "personalInfo.contactAddresses.communityData.name," +
        "personalInfo.contactAddresses.communityData.pkCommunityData," +
        "personalInfo.contactAddresses.communityData.version," +
        "personalInfo.contactAddresses.buildingNumber," +
        "personalInfo.contactAddresses.unitNumber," +
        "personalInfo.contactAddresses.doorNumber,personalInfo.contactAddresses.detailAddress," +
        "personalInfo.contactAddresses.address.*,personalInfo.contactAddresses.deleteFlag," +
        "personalInfo.contactAddresses.addressStatus.*," +
        "personalInfo.contactAddresses.version," +
        "contacts.contacts.version," +
        "contacts.contacts.pkContacts," +
        "contacts.contacts.relation," +
        "contacts.contacts.sosContact," +
        "contacts.contacts.personalInfo.pkPersonalInfo," +
        "contacts.contacts.personalInfo.version," +
        "contacts.contacts.personalInfo.name," +
        "contacts.contacts.personalInfo.sex.*," +
        "contacts.contacts.personalInfo.birthday," +
        "contacts.contacts.personalInfo.idNumber," +
        "contacts.contacts.personalInfo.zipCode," +
        "contacts.contacts.personalInfo.work," +
        "contacts.contacts.personalInfo.phone," +
        "contacts.contacts.personalInfo.mobilePhone," +
        "contacts.contacts.personalInfo.address," +
        "contacts.contacts.personalInfo.Electronicmail," +
        "interest.pkInterest," +
        "interest.name," +
        "interest.version," +
        "personalInfo.houseRegister.*," +
        "personalInfo.monthIncome," +
        "personalInfo.politicalParty.*," +
        "personalInfo.faith.*," +
        "creater.pkUser," +
        "creater.name," +
        "createDate";

    var gridFetchProperties = "pkMember," +
        "personalInfo.name," +
        "personalInfo.sex.*," +
        "personalInfo.birthday," +
        "personalInfo.idNumber," +
        "personalInfo.areaAddress," +
        "personalInfo.areaAddress.fullName," +
        "personalInfo.contactAddresses.address.fullName," +
        "personalInfo.contactAddresses.addressStatus," +
        "personalInfo.contactAddresses.detailAddress," +
        "personalInfo.contactAddresses.communityData.name," +
        "organization.pkOrganization," +
        "organization.name," +
        "memberNumber," +
        "personalInfo.phone," +
        "personalInfo.mobilePhone," +
        "status.*," +
        "version," +
        "source.*," +
        "description," +
        "interest.name";

    var member = ELView.extend({
        events: {
            "blur .J-form-meminformation-text-idNumber": function(e) {
                if (e) {
                    var birthday = "";
                    var memberForm = this.get("form");
                    var idType = memberForm.getValue("idType");
                    var idNumber = memberForm.getValue("idNumber");
                    memberForm.setDisabled("age", true);
                    if (idType == "IdentityCard") {
                        if (idNumber != null && idNumber != "") {
                            if (idNumber.length == 15) {
                                birthday = "19" + idNumber.substr(6, 6);
                                if (parseInt(idNumber.substr(8, 2)) > 12 || parseInt(idNumber.substr(8, 2) < 1)) {
                                    Dialog.tip("身份证月份不对,请修改!");
                                    memberForm.setValue("birthday", "");
                                }
                                if (parseInt(idNumber.substr(10, 2)) > 31 || parseInt(idNumber.substr(10, 2) < 1)) {
                                    Dialog.tip("身份证日期不对,请修改!");
                                    memberForm.setValue("birthday", "");
                                }
                            } else if (idNumber.length == 18) {
                                birthday = idNumber.substr(6, 8);
                                if (parseInt(idNumber.substr(10, 2)) > 12 || parseInt(idNumber.substr(10, 2) < 1)) {
                                    Dialog.tip("身份证月份不对,请修改!");
                                    memberForm.setValue("birthday", "");
                                }
                                if (parseInt(idNumber.substr(12, 2)) > 31 || parseInt(idNumber.substr(12, 2) < 1)) {
                                    Dialog.tip("身份证日期不对,请修改!");
                                    memberForm.setValue("idNumber", "");
                                }
                            } else {
                                Dialog.tip("身份证长度不对,请修改!");
                                memberForm.setValue("idNumber", "");
                                memberForm.setValue("birthday", "");
                                memberForm.setValue("age", "");
                                memberForm.setDisabled("birthday", false);
                                return;
                            }
                            birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
                            memberForm.setValue("birthday", birthday + " 00:00:00");
                            //						memberForm.setDisabled("birthday",true);
                        } else {
                            memberForm.setDisabled("birthday", false);
                        }
                        if (moment(birthday).isAfter(moment(), 'day')) {
                            Dialog.tip("身份证号不正确,出生日期应小于当前日期！");
                            memberForm.setValue("birthday", "");
                            memberForm.setValue("idNumber", "");
                        } else {
                            memberForm.setValue("age", moment().diff(birthday, 'years'));
                            memberForm.setReadonly("age");
                            memberForm.setDisabled("age", true);
                        }
                    }
                }
            },
            "blur .J-form-meminformation-date-birthday": function(e) {
                if (e) {
                    var memberForm = this.get("form");
                    var birthday = memberForm.getValue("birthday");
                    if (moment(birthday).isAfter(moment(), 'day')) {
                        Dialog.tip("出生日期应小于当前日期！");
                        memberForm.setValue("birthday", "");
                    } else {
                        memberForm.setValue("age", moment().diff(birthday, 'years'));
                        memberForm.setReadonly("age");
                    }
                }
            },
            "blur .J-form-contacts-date-birthday": function(e) {
                if (e) {
                    var contactsfrom = this.get("contactsfrom");
                    var birthday = contactsfrom.getValue("birthday");
                    if (moment(birthday).isAfter(moment(), 'day')) {
                        Dialog.tip("出生日期应小于当前日期！");
                        contactsfrom.setValue("birthday", "");
                    } else {
                    	contactsfrom.setValue("age", moment().diff(birthday, 'years'));
                    	contactsfrom.setReadonly("age");
                    }
                }
            },
            "change .J-idType": function(e) {
                if (e) {
                    this.checkId(e);
                }
            },
            "blur .J-idNumber": function(e) {
                if (e) {
                    this.checkId(e);
                }
            },
        },
        attrs: {
            template: template
        },
        _showDetail: function(widget, data, disabled,callback) {
            aw.ajax({
                url: "api/member/getmemberdetail",
                data: {
                    "pkMember": data.pkMember,
                    fetchProperties: detailFetchProperties
                },
                dataType: "json",
                success: function(dat) {
                    var data = dat;
                    var form = widget.get("form");
                    if (disabled) {
                        widget.get("subnav").hide(["add", "search", /*"status",*/ "servicePoint", "toExcel", "return", "save"]);
                        widget.show([".J-form", ".J-contactsgrid"]).hide([".J-grid"]);
                    } else {
                        widget.get("subnav").hide([ "add", "search", /*"status",*/ "servicePoint", "toExcel"]).show(["return", "save"]);
                        widget.show([".J-form", ".J-contactsgrid"]).hide([".J-grid"]);
                    }
                    //联系人信息
                    var contactsgrid = widget.get("contactsgrid");
                    var contact = [];
                    for (var d = 0; d < data.contacts.length; d++) {
                        contact.push(data.contacts[d].contacts);
                    }
                    data.contacts = contact;
                    contactsgrid.setData(data.contacts);
                    var dx = $.extend(true, [], data.contacts);
                    for (var i = 0; i < dx.length; i++) {
                        dx[i].name = data.contacts[i].personalInfo.name;
                        if (data.contacts[i].personalInfo.sex) {
                            dx[i].sex = data.contacts[i].personalInfo.sex.key;
                        }
                        dx[i].relation=data.contacts[i].relation;
                        dx[i].sosContact=data.contacts[i].sosContact;
                        dx[i].birthday = data.contacts[i].personalInfo.birthday;
                        dx[i].address = data.contacts[i].personalInfo.address;
                        dx[i].mobilePhone = data.contacts[i].personalInfo.mobilePhone;
                        dx[i].idNumber = data.contacts[i].personalInfo.idNumber;
                        dx[i].work = data.contacts[i].personalInfo.work;
                        dx[i].zipCode = data.contacts[i].personalInfo.zipCode;
                        dx[i].personalVersion = data.contacts[i].personalInfo.version;
                    }
                   contactsgrid.setData(dx);
                    
                    if (data.personalInfo.lunarBirthday) {
                        $("#check").attr("checked", true);
                    } else {
                        $("#check").attr("checked", false);
                    }
                    form.reset();
                    form.setData(data);
                    form.download("J-form-emulation-profile-img", "api/attachment/personalphoto/" + data.pkMember);
                    //给member级别的字段赋值
                    form.setData({
                        pkMember: data.pkMember,
                        version: data.version,
                        deleteFlag: data.deleteFlag.key,
                        //status: data.status.key
                    });
                    //给personalInfo级别的字段赋值
                    form.setValue("name", data.personalInfo.name);
                    form.setValue("sex", data.personalInfo.sex);
                    form.setValue("idType", data.personalInfo.idType);
                    form.setValue("idNumber", data.personalInfo.idNumber);
                    form.setValue("birthday", data.personalInfo.birthday);
                    
                    if(data.personalInfo.contactAddresses.length > 0){
                    	for ( var i in data.personalInfo.contactAddresses) {
							if(data.personalInfo.contactAddresses[i].addressStatus.key == "DefaultAddress"){
								widget.set("cnpkContactAddress",data.personalInfo.contactAddresses[i].pkContactAddress);
								widget.set("cnpkContactVersion",data.personalInfo.contactAddresses[i].version);
								form.setValue("cnaddress", data.personalInfo.contactAddresses[i].address);
								form.setValue("cndetailAddress", data.personalInfo.contactAddresses[i].detailAddress);
							}
						}
                    }else{
                    	form.setValue("cnaddress", data.personalInfo.areaAddress);
                    	form.setValue("cndetailAddress", data.personalInfo.address);
                    }
                    
                    if (data.personalInfo.houseRegister) {
                        form.setValue("houseRegister", data.personalInfo.houseRegister);
                    }
                    form.setValue("houseRegisterDetail", data.personalInfo.houseRegisterDetail);
                    form.setValue("mobilePhone", data.personalInfo.mobilePhone);
                    form.setValue("phone", data.personalInfo.phone);
                    form.setValue("electronicMail", data.personalInfo.electronicMail);
                    form.setValue("personalInfoVersion", data.personalInfo.version);
                    form.setValue("pkPersonalInfo", data.personalInfo.pkPersonalInfo);
                    form.setValue("cultureLevel", data.personalInfo.cultureLevel);
                    form.setValue("qq", data.personalInfo.qq);
                    form.setValue("weChat", data.personalInfo.weChat);
                    form.setValue("zipCode", data.personalInfo.zipCode);
                    form.setValue("work", data.personalInfo.work);
                    form.setValue("position", data.personalInfo.position);
                    if (data.personalInfo.nativePlace) {
                        form.setValue("nativePlace", data.personalInfo.nativePlace);
                    }
                    
                    form.setValue("organization", data.organization.pkOrganization);
                    
                    if (data.personalInfo.birthday !== null) {
                        form.setValue("age", moment().diff(data.personalInfo.birthday, 'years'));
                    }
                    form.setReadonly("age");
                    form.setDisabled("age", true);
                    if (disabled) {
                        form.setDisabled(true);
                    }
                    if (data.dataSource == 'Government') {
                        form.setDisabled("name", true);
                        form.setDisabled("sex", true);
                        form.setDisabled("idType", true);
                        form.setDisabled("idNumber", true);
                        form.setDisabled("birthday", true);
                        form.setDisabled("memberTypes", true);
                    }

                    if(callback){
                        callback();
                    }

                }
            });

        },
        checkId: function(e) {
            var memberForm = this.get("form");
            var idType = memberForm.getValue("idType");
            var idNumber = memberForm.getValue("idNumber");
            var mobilePhone = memberForm.getValue("mobilePhone");
            var pk = memberForm.getValue("pkMember");
            var that = this;
            if (idType && idNumber != "" && pk == "" && mobilePhone != "") {
                aw.ajax({
                    url: "api/member/query",
                    data: {
                        "personalInfo.idType": idType,
                        "personalInfo.idNumber": idNumber,
                        "personalInfo.mobilePhone": mobilePhone,
                        "deleteFlag": "UnDeleted",
                        fetchProperties: gridFetchProperties
                    },
                    dataType: "json",
                    success: function(data) {
                        if (data.length > 0) {
                            Dialog.tip("该会员已存在，请输入正确的证件号和手机号！");
                            //							that._showDetail(that,data[0],false);
                            that.get("form").setValue("idNumber", "");
                            that.get("form").setValue("mobilePhone", "");
                            count++;
                        }
                    }
                });
            }
            if (idType && idNumber != "" && pk != "" && mobilePhone != "") {
                aw.ajax({
                    url: "api/member/query",
                    data: {
                        "personalInfo.idType": idType,
                        "personalInfo.idNumber": idNumber,
                        "personalInfo.mobilePhone": mobilePhone,
                        "deleteFlag": "UnDeleted",
                        fetchProperties: gridFetchProperties
                    },
                    dataType: "json",
                    success: function(data) {
                        if (data.length > 0 && parseInt(pk) != data[0].pkMember) {
                            Dialog.tip("该会员已存在，请输入正确的证件号和手机号！");
                            that.get("form").setValue("idNumber", "");
                            that.get("form").setValue("mobilePhone", "");
                            count++;
                        }
                    }
                });
            }

        },
        membersave: function(dat) {
            var imagNumber = $(".J-preview img").size();
            var widget = this;
            var form =widget.get("form");
            var pkMember = widget.get("form").getValue("pkMember");
            if (pkMember == "") {
                widget.set("flag", "add");
            }
            dat += "&source=Offline&dataSource=Organization"
            aw.saveOrUpdate("api/member/savemember", dat, function(data) {
                widget.set("pkMember", data.pkMember);
                if (data.pkMember) {
                    widget.get("form").upload("J-form-emulation-profile-img", "api/attachment/personalphoto/" + data.pkMember);
                }
                var contacts = {};
                var contactsgrid = widget.get("contactsgrid").getData();
                var dx = $.extend(true, [], contactsgrid)
                for (var i = 0; i < contactsgrid.length; i++) {
                    if (contactsgrid[i].personalInfo) {
                        dx[i].sex = contactsgrid[i].personalInfo.sex ? contactsgrid[i].personalInfo.sex.key : null;
                        dx[i].personalInfo = "";
                        dx[i].sosContact = contactsgrid[i].sosContact;
                        dx[i].version = dx[i].personalVersion;
                    }

                    var obj = {};
                    obj.personalInfo = dx[i];
                    obj.relation = dx[i].relation;
                    obj.sosContact = dx[i].sosContact;
                    if (contactsgrid[i].pkContacts) {
                        obj.pkContacts = contactsgrid[i].pkContacts
                        obj.version = contactsgrid[i].version
                    }
                    dx[i] = obj;
                }
                contacts.listsContacts = dx;
                var member = {};
                member.pkMember = data.pkMember;
                contacts.member = member;
                contacts.pklist = pktemp;
                pktemp = [];
                aw.saveOrUpdate("api/contacts/savecontact", aw.customParam(contacts), function(data2) {
                    widget.get("form").setValue("organization", data.organization.pkOrganization);
                    var a = [];
                    widget.get("contactsgrid").setData(a);
                    widget.hide([".J-form", ".J-contactsgrid"]).show([".J-grid"]);
                    widget.get("subnav").hide([ "return", "save","add"/*,"status"*/]).show([ "search", "servicePoint"]);
                });
                
               
                //保存会员地址
               var memberaddresses ={
            		   pkContactAddress:widget.get("cnpkContactAddress"),
            		   address:form.getValue("cnaddress"),
            		   detailAddress:form.getValue("cndetailAddress"),
            		   personalInfo:data.personalInfo.pkPersonalInfo,
            		   addressStatus:"DefaultAddress",
            		   version:widget.get("cnpkContactVersion"),
               }
               
               widget.set("cnpkContactAddress","");
               widget.set("cnpkContactVersion","");
                aw.saveOrUpdate("api/contactaddress/save", aw.customParam(memberaddresses), function(data3) {
                    if (isGovern) {
                        widget.loadOrganization(widget);
                        widget.get("form").setValue("organization", data.organization.pkOrganization);
                    } 
                    var a = [];
                    widget.hide([".J-form", ".J-contactsgrid"]).show([".J-grid"]);
                    widget.get("subnav").hide([ "return", "save","add"/*,"status"*/]).show([ "search", "servicePoint", "toExcel"]);
                    widget.setParams(widget);
                    Dialog.mask(false);
                    widget.get("grid").refresh();
                    return false;
                });
            })
            count = 0;
        },
        checkIdPhone: function(dat) {
            var memberForm = this.get("form");
            var idType = memberForm.getValue("idType");
            var idNumber = memberForm.getValue("idNumber");
            var mobilePhone = memberForm.getValue("mobilePhone");
            var pk = memberForm.getValue("pkMember");
            var name = memberForm.getValue("name");
            var that = this;
            if (idType && idNumber != "" && pk == "" && mobilePhone != "" && name != "") {
                aw.ajax({
                    url: "api/member/query",
                    data: {
                    	"personalInfo.name" : name,
                        "personalInfo.idType": idType,
                        "personalInfo.idNumber": idNumber,
                        "personalInfo.mobilePhone": mobilePhone,
                        "deleteFlag": "UnDeleted",
                        fetchProperties: gridFetchProperties
                    },
                    dataType: "json",
                    success: function(data) {
                        if (data.length > 0) {
                            Dialog.tip("该会员已存在，请输入正确的证件号和手机号！");
                            //							that._showDetail(that,data[0],false);
                            that.get("form").setValue("idNumber", "");
                            that.get("form").setValue("mobilePhone", "");
                            Dialog.mask(false);
                        } else {
                        	that.membersave(dat);
                        }
                    }
                });
            } else if (idType && idNumber != "" && pk != "" && mobilePhone != "" && name != "") { //修改
                aw.ajax({
                    url: "api/member/query",
                    data: {
                    	"personalInfo.name" : name,
                        "personalInfo.idType": idType,
                        "personalInfo.idNumber": idNumber,
                        "personalInfo.mobilePhone": mobilePhone,
                        "deleteFlag": "UnDeleted",
                        fetchProperties: gridFetchProperties
                    },
                    dataType: "json",
                    success: function(data) {
                        if (data.length > 0 && parseInt(pk) != data[0].pkMember) {
                            Dialog.tip("该会员已存在，请输入正确的证件号和手机号！");
                            that.get("form").setValue("idNumber", "");
                            that.get("form").setValue("mobilePhone", "");
                            Dialog.mask(false);
                        } else {
                        	that.membersave(dat);
                        }
                    }
                });
            } else {
                aw.ajax({
                    url: "api/member/query",
                    data: {
                    	"personalInfo.name" : name,
                        "personalInfo.idType": idType,
                        "personalInfo.idNumber": idNumber,
                        "deleteFlag": "UnDeleted",
                        fetchProperties: gridFetchProperties
                    },
                    dataType: "json",
                    success: function(data) {
                        if (data.length > 0 && data[0].pkMember != parseInt(pk)) {
                            Dialog.tip("该会员已存在，请输入正确的证件号和手机号！");
                            //							that._showDetail(that,data[0],false);
                            that.get("form").setValue("idNumber", "");
                            that.get("form").setValue("mobilePhone", "");
                            Dialog.mask(false);
                        } else {
                            that.membersave(dat);
                        }
                    }
                });
            }
        },
        setParams: function(widget) {
            widget.get("grid").get("model").url = "api/member/queryallmember";
            var subnav = widget.get("subnav");
            widget.get("grid").get("model").params = function() {
                var objQuery = {
                    //"statusIn": subnav.getValue("status"),
                    "deleteFlag": "UnDeleted",
                    "exitMember":true,
                    fetchProperties: gridFetchProperties
                };
                var j = 0;
                for (var i = 0; i < activeUser.roles.length; i++) {
                    if (activeUser.roles[i].pkRole != 7) {
                        j++;
                        break;
                    }
                }
                if (widget.get("subnav").getValue("servicePoint") != null) {
                    objQuery["pkServicePoint"] = widget.get("subnav").getValue("servicePoint");
                }
                return objQuery;
            };
        },
        initComponent: function(params, widget) {
            var subnav = new Subnav({
                parentNode: ".J-subnav",
                model: {
                    title: "会员基本信息",
                    items: [{
                        id: "search",
                        type: "search",
                        placeholder: "姓名/手机/证件号",
                        handler: function(str) {
                            var grid = widget.get("grid");
                            var obj = {
                                s: str,
                                properties: "personalInfo.name,personalInfo.mobilePhone,personalInfo.idNumber",
                                pkMember: params ? params.pkMember : null,
                                deleteFlag: "UnDeleted",
                                exitMember: true,
                                pkServicePoint: subnav.getValue("servicePoint"),
                                fetchProperties: gridFetchProperties
                            };
                            //分页 原因
                            widget.get("grid").get("model").url = "api/member/searchallmemberbycard";
                            widget.get("grid").get("model").params = obj;
                            widget.get("grid").refresh(null, function() {
                                widget.get("subnav").setValue("search", "");
                            });
                        }
                    }, {
                        id: "servicePoint",
                        tip: "服务点",
                        type: "buttongroup",
                        keyField: "pkServicePoint",
                        valueField: "name",
                        items : activeUser.privateServicePoints,
                        params: function() {
                            return {
                                fetchProperties: "pkServicePoint,name"
                            };
                        },
                        handler: function(key, element) {
                            aw.ajax({
                                url: "api/servicepoint/querybypk",
                                data: {
                                    "pkServicePoint": key,
                                    fetchProperties: "communityDatas.pkCommunityData,communityDatas.name"
                                },
                                dataType: "json",
                                success: function(data) {
                                    widget.get("grid").refresh(widget.setParams(widget), function(data) {});
                                }
                            });
                        }
                    }, {
                        id: "status",
                        tip: "会员状态",
                        type: "buttongroup",
                        /*items: [{
                            key: "Normal",
                            value: "正常"
                        }, {
                            key: "Late",
                            value: "已故"
                        }, {
                            key: "Normal,Late",
                            value: "全部"
                        }],
                        handler: function(key, element) {
                            widget.get("grid").refresh(widget.setParams(widget), function(data) {});
                        }*/

                    }, {
                        id: "toExcel",
                        text: "导出",
                        type: "button",
                        handler: function() {
                            var subnav = widget.get("subnav");
                            var url = "api/member/tomemberexcel?deleteFlag=UnDeleted" +
                                /*"&statusIn=" + subnav.getValue("status")+*/"&exitMember=true";
                            var j = 0;
                            var govern = false;
                            for (var i = 0; i < activeUser.roles.length; i++) {
                                if (activeUser.roles[i].pkRole != 7) {
                                    if (activeUser.roles[i].pkRole == 33) {
                                        govern = true;
                                    }
                                    j++;
                                    break;
                                }
                            }
                            if (govern) {
                                url = url + "&pkOrg=" + subnav.getValue("organization");
                            } else {
                                if (activeUser.servicePoint) {
                                    url = url + "&pkServicePoint=" + activeUser.servicePoint.pkServicePoint;
                                } else {
                                    url = url + "&pkServicePoint=" + subnav.getValue("servicePoint");
                                }
                                if (j > 0) {
                                    url = url + "&organization.pkOrganization=" + activeUser.organization.pkOrganization;
                                }
                            }
                            window.open(url);
                        }
                    }, {
                        id: "add",
                        text: "新增",
                        type: "button",
                        show: false,
                        handler: function() {
                            var form = widget.get("form");
                            form.reset();
                            form.setValue("sex", "Male");
                            form.setReadonly("age");
                            form.setDisabled("age", true);
                            var contactsgrid = widget.get("contactsgrid");
                            contactsgrid.setData([]);
                            widget.show([".J-form", ".J-contactsgrid"]).hide([".J-grid"]);
                            widget.get("subnav").hide([ "add", "search", /*"status",*/ "toExcel"]).show(["return", "save"]);
                        }
                    }, {
                        id: "save",
                        text: "保存",
                        type: "button",
                        show: false,
                        handler: function() {
                            Dialog.mask(true);
                            var memberForm = widget.get("form");
                            var name = widget.get("form").getValue("name");
                            var sex = widget.get("form").getValue("sex");
                            var idType = widget.get("form").getValue("idType");
                            var idNumber = widget.get("form").getValue("idNumber");
                            var birthday = moment(widget.get("form").getValue("birthday")).format("YYYY-MM-DD HH:mm:ss");
                            var houseRegister = widget.get("form").getValue("houseRegister");
                            var phone = widget.get("form").getValue("phone");
                            var mobilePhone = widget.get("form").getValue("mobilePhone");
                            var creater = widget.get("form").getValue("creater");
                            var createDate = moment(widget.get("form").getValue("createDate")).format("YYYY-MM-DD HH:mm:ss");

                            if (isGovern && memberTypes.length < 1) {
                                Dialog.confirm({
                                    title: "必填项",
                                    content: "会员类型不能为空"
                                })
                                Dialog.mask(false);
                                return false;
                            }
                            if (name == null || name == "") {
                                Dialog.confirm({
                                    title: "必填项",
                                    content: "姓名不能为空"
                                })
                                Dialog.mask(false);
                                return false;
                            }
                            if (sex == null || sex == "") {
                                Dialog.confirm({
                                    title: "必填项",
                                    content: "请选择性别"
                                })
                                Dialog.mask(false);
                                return false;
                            }
                            if (idType == null || idType == "") {
                                Dialog.confirm({
                                    title: "必填项",
                                    content: "请选择证件类型"
                                })
                                Dialog.mask(false);
                                return false;
                            }
                            if (idNumber == null || idNumber == "") {
                                Dialog.confirm({
                                    title: "必填项",
                                    content: "请输入证件号码"
                                })
                                Dialog.mask(false);
                                return false;
                            }
                            if (idNumber != null && idNumber != "") {
                                if (idNumber.length > 0 && idNumber.match(/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/) == false) {
                                    Dialog.confirm({
                                        title: "证件号码填写格式错误",
                                        content: "只能填写数字和英文"
                                    })
                                    Dialog.mask(false);
                                    return false;
                                }
                            }
                            if (phone != null && phone != "") {
                                if (isNaN(phone)) {
                                    Dialog.confirm({
                                        title: "固定电话格式填写错误",
                                        content: "只能填写数字"
                                    })
                                    Dialog.mask(false);
                                    return false;
                                }
                            }
                            if (mobilePhone != null && mobilePhone != "") {
                                if (isNaN(mobilePhone)) {
                                    Dialog.confirm({
                                        title: "手机格式填写错误",
                                        content: "只能填写数字"
                                    })
                                    Dialog.mask(false);
                                    return false;
                                }
                                if (mobilePhone.length != 11) {
                                    Dialog.confirm({
                                        title: "手机格式填写错误",
                                        content: "有效号码是11位数字"
                                    })
                                    Dialog.mask(false);
                                    return false;
                                }
                            }
                            if (mobilePhone == "" && phone == "") {
                                Dialog.confirm({
                                    title: "必填项",
                                    content: "请输入固定电话或手机"
                                })
                                Dialog.mask(false);
                                return false;
                            }
                            memberForm.setValue("organization", activeUser.organization.pkOrganization);
                            memberForm.setValue("creater", activeUser.pkUser);
                            memberForm.setValue("createDate", moment().valueOf());
                            memberForm.setValue("pkServicePoint", widget.get("subnav").getValue("servicePoint"));
                            var dat = $("#meminformation").serialize();
                            if ($('#check').is(':checked')) {
                                dat += ("&lunarBirthday=" + true);
                            } else {
                                dat += ("&lunarBirthday=" + false);
                            }
                            widget.checkIdPhone(dat);
                        },
                    }, {
                        id: "return",
                        text: "返回",
                        type: "button",
                        show: false,
                        handler: function() {
                        	widget.set("cnpkContactAddress","");
                            widget.set("cnpkContactVersion","");
                            widget.show([".J-grid"]).hide([".J-form", ".J-contactsgrid"]);
                            widget.get("subnav").hide([ "return", "save","add", /*"status"*/]).show(["search", "servicePoint", "toExcel"]);
                            if (isGovern) {
                                widget.get("subnav").hide(["servicePoint"]);
                            }
                        }
                    }, {
                        id: "detailsreturn",
                        text: "返回",
                        type: "button",
                        show: false,
                        handler: function() {
                        	
                            widget.show([".J-grid"]).hide([".J-form", ".J-contactsgrid"]);
                            widget.get("subnav").hide([ "detailsreturn", "save","add",/* "status"*/]).show([ "search", "servicePoint", "toExcel"]);

                            widget.get("contactsgrid").showButton("add");
                            $(".J-contactsgrid").find(".J-grid-columns-operate button").show();

                            if (isGovern) {
                                widget.get("subnav").hide(["servicePoint", "interest"]);
                            }
                        }
                    }, {
                        id: "contactsreturn",
                        text: "返回",
                        type: "button",
                        show: false,
                        handler: function() {
                            widget.show([".J-form", ".J-contactsgrid"]).hide([".J-contactsform"]);
                            widget.get("subnav").setTitle("会员基本信息");
                            widget.get("subnav").hide([ "contactsreturn"]).show(["return", "save", "servicePoint"]);
                        }
                    }],
                }
            });
            this.set("subnav", subnav);

            var grid = new Grid({
                parentNode: ".J-grid",
                autoRender: false,
                model: {
                    lazyPage: true,
                    url: "api/member/queryallmember",
                    params: function() {
                        var subnav = widget.get("subnav");
                        var obj = {
                            pkMember: params ? params.pkMember : null,
                            "statusIn": subnav.getValue("status"),
                            "deleteFlag": "UnDeleted",
                            "exitMember":true,
                            fetchProperties: gridFetchProperties
                        };
                        var j = 0;
                        for (var i = 0; i < activeUser.roles.length; i++) {
                            if (activeUser.roles[i].pkRole != 7) {
                                j++;
                                break;
                            }
                        }

                        if (j > 0) {
                            if (widget.get("subnav").getValue("servicePoint") != null) {
                                obj["pkServicePoint"] = widget.get("subnav").getValue("servicePoint");
                            }
                        } else {
                            obj["pkServicePoint"] = null;
                        }
                        return obj;
                    },
                    isInitPageBar: true,
                    columns: [{
                        name: "personalInfo.name",
                        label: "姓名",
                        format: "detail",
                        formatparams: {
                            key: "detail",
                            handler: function(index, data, rowEle) {
                                //TODO 查看card
                                widget.get("subnav").show(["detailsreturn"]);
                                widget._showDetail(widget, data, true,function(){
                                    widget.get("contactsgrid").hideButton("add");
                                    $(".J-contactsgrid").find(".J-grid-columns-operate button").hide();
                                });

                            }
                        }
                    }, {
                        name: "personalInfo.sex.value",
                        label: "性别",
                    }, {
                        name: "personalInfo.idNumber",
                        label: "证件号码"
                    }, {
                        name: "personalInfo.birthday",
                        label: "出生日期",
                        format: "date",
                        formatparams: {
                            mode: "YYYY-MM-DD"
                        }
                    }, {
                        name: "personalInfo.birthday",
                        label: "年龄",
                        format: "age"
                    }, {
                        name: "personalInfo.mobilePhone",
                        label: "手机"
                    }, {
                        name: "defaultAddress",
                        label: "地址",
                        format:function(value,row){
                        	var address ="";
                        	for ( var i in row.personalInfo.contactAddresses) {
								if(row.personalInfo.contactAddresses[i].addressStatus.key=="DefaultAddress"&&row.personalInfo.contactAddresses[i].address!=null){
									address += (row.personalInfo.contactAddresses[i].address.fullName ||"")+ (row.personalInfo.contactAddresses[i].detailAddress||"");
								}
							}
                        	if(address == ""){
                        		if(row.personalInfo.areaAddress!=null){
                        			address=row.personalInfo.areaAddress.fullName;
                        		}
                        	}
                        	return address;
                        }
                    }, {
                        name: "status.value",
                        label: "会员状态"
                    }, {
                        name: "operate",
                        label: "操作",
                        format: "button",
                        formatparams: [{
                            id: "edit",
                            icon: "icon-edit",
                            show: function(value, row) {
                                if (params && params.father == "memberEnterStat") {
                                    return false;
                                } else {
                                    return true;
                                }
                            },
                            handler: function(index, data, rowEle) {
                                widget._showDetail(widget, data, false);
                            }
                        }, {
                            id: "delete",
                            icon: "icon-remove",
                            show: function(value, row) {
                                if (params && params.father == "memberEnterStat") {
                                    return false;
                                } else {
                                    return true;
                                }
                            },
                            handler: function(index, data, rowEle) {
                                Dialog.confirm({
                                    content: "是否确认删除该条数据？",
                                    confirm: function() {
                                        aw.ajax({
                                            url: "api/perorder/query",
                                            data: {
                                                member: data.pkMember,
                                            },
                                            dataType: "json",
                                            success: function(data2) {
                                                if (data2.length <= 0) {
                                                    aw.saveOrUpdate("api/member/" + data.pkMember + "/deleteflag", data, function(data) {
                                                        grid.refresh();
                                                    });
                                                } else {
                                                    Dialog.alert({
                                                        content: "该数据已经被订单引用！不能删除！",
                                                    });
                                                }
                                            }
                                        });
                                    },
                                    cancel: function() {
                                        Dialog.close;
                                    }
                                });
                            }
                        }]
                    }]
                }
            });
            this.set("grid", grid);

            var form = new Form({
                parentNode: ".J-form",
                model: {
                    id: "meminformation",
                    defaultButton: false,
                    type: "profile",
                    layout: "2_1",
                    items: [{
                        title: "会员照片",
                        //						icon:"photo",
                        img: {
                            idAttribute: "pkMember",
                            url: "api/attachment/personalphoto/",
                        },
                        children: [{
                            name: "pkMember",
                            type: "hidden"
                        }, {
                            name: "pkPersonalInfo",
                            type: "hidden"
                        }, {
                            name: "personalInfoVersion",
                            defaultValue: "0",
                            type: "hidden"
                        }, {
                            name: "pkServicePoint",
                            type: "hidden"
                        }, {
                            name: "deleteFlag",
                            defaultValue: "UnDeleted",
                            type: "hidden"
                        }, {
                            name: "organization",
                            type: "hidden"
                        }, /*{
                            name: "status",
                            type: "hidden",
                            defaultValue: "Normal"
                        }, */{
                            name: "version",
                            defaultValue: "0",
                            type: "hidden"
                        }, {
                            name: "creater",
                            defaultValue: "activeUser.pkUser",
                            type: "hidden"
                        }, {
                            name: "createDate",
                            format: "date",
                            type: "hidden",
                            defaultValue: moment().valueOf()
                        }, {
                            name: "name",
                            label: "姓名",
                            validate: ["required"],
                            exValidate: function(value) {
                                if (value.replace(/[^\x00-\xff]/g, "**").length > 20) {
                                    return "姓名限制10个汉字";
                                } else {
                                    return true;
                                }
                            }
                        }, {
                            name: "sex",
                            label: "性别",
                            type: "radio",
                            list: [{
                                key: "Male",
                                value: "男"
                            }, {
                                key: "Female",
                                value: "女"
                            }],
                            defaultValue: "Male",
                            validate: ["required"]
                        }, {
                            name: "idType",
                            label: "证件类型",
                            type: "select",
                            options: enmu["com.eling.elcms.basedoc.model.IdType"],
                            defaultValue: "IdentityCard",
                            validate: ["required"]
                        }, {
                            name: "idNumber",
                            label: "证件号码",
                            validate: ["required"],
                            exValidate: function(value) {
                                if (value.match(/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/) == false) {
                                    return "身份证号格式错误";
                                } else {
                                    return true;
                                }
                            }
                        }, {
                            id: "birthday",
                            name: "birthday",
                            label: "出生日期",
                            type: "date",
                            validate: ["required"],
                        }, {
                            name: "age",
                            label: "年龄",
                            readonly: true,
                            disabled: true, 
                            validate: ["required"]
                        }, {
                            name: "mobilePhone",
                            label: "联系电话",
                            validate: ["required"],
                            exValidate: function(value) {
                                if (value.length > 11) {
                                    return "号码限制11位";
                                } else {
                                    return true;
                                }
                            }
                        }, {
                            name: "cultureLevel",
                            label: "学历",
                            type: "select",
                            options: enmu["com.eling.elcms.basedoc.model.CultureLevel"]
                        }, {
                            name: "phone",
                            label: "固定电话",
                            exValidate: function(value) {
                                if (value.length > 11) {
                                    return "号码限制11位";
                                } else {
                                    return true;
                                }
                            }
                        }, {
                            name: "electronicMail",
                            label: "E-MAIL",
                            validate: ["email"]
                        }, {
                            name: "qq",
                            label: "QQ"
                        }, {
                            name: "weChat",
                            label: "微信"
                        }, {
                        	name: "cnaddress",
                            label: "省/市/区(县)",
                            type: "place",
                            validate: ["required"]
                        }, {
                        	name: "zipCode",
                            label: "邮编",
                            validate: ["required"],
                        }, {
                        	name: "cndetailAddress",
                            label: "详细地址",
                            validate: ["required"],
                            "break": true
                        }, {
                        	name: "work",
                            label: "工作单位"
                        }, {
                        	name: "position",
                            label: "工作职位"
                        },{
                            name: "houseRegister",
                            label: "户籍",
                            type: "place",
                        },{
                            name: "nativePlace",
                            label: "籍贯",
                            type: "place",
                        },{
                        	name: "houseRegisterDetail",
                            label: "户籍地址",
                            "break": true
                        }]
                    }]
                }
            });
            this.set("form", form);

            var contactsgrid = new Grid({
                parentNode: ".J-contactsgrid",
                model: {
                    head: {
                        buttons: [{
                            id: "add",
                            icon: "icon-plus",
                            handler: function() {
                                widget.get("contactsfrom").reset();
                                widget.get("contactsfrom").setValue("sex", "Male");
                                widget.get("contactsfrom").setValue("sosContact", "false");
                                widget.get("subnav").setTitle("会员联系人信息");
                                widget.get("subnav").show(["contactsreturn"]).hide(["return", "save", "servicePoint"]);
                                widget.show([".J-contactsform"]).hide([".J-form", ".J-contactsgrid"]);
                            }
                        }]
                    },
                    columns: [{
                        key: "name",
                        name: "姓名"
                    }, {
                        key: "sex",
                        name: "性别",
                        format: function(value, row) {
                            if (value == "Male") {
                                return "男"
                            } else {
                                return "女"
                            }
                        }
                    }, {
                        key: "birthday",
                        name: "年龄",
                        format: "age"
                    }, {
                        key: "relation",
                        name: "与会员关系"
                    }, {
                        key: "sosContact",
                        name: "是否紧急联系人",
                        format: function(value, row) {
                            if (value) {
                                return "是"
                            } else {
                                return "否"
                            }
                        }
                    },{
                    	key: "work",
                        name: "工作单位"
                    }, {
                        key: "address",
                        name: "通讯地址"
                    }, {
                        key: "mobilePhone",
                        name: "手机"
                    }, {
                        key: "operate",
                        name: "操作",
                        format: "button",
                        formatparams: [{
                            key: "edit",
                            icon: "icon-edit",
                            handler: function(index, data, rowEle) {
                                widget.get("contactsfrom").reset();
                                data.index = index;
                                widget.get("contactsfrom").setValue("sosContact", data.sosContact);
                                data.age= moment().diff(data.birthday, 'years');
                                widget.get("contactsfrom").setData(data);
                                widget.get("subnav").setTitle("会员联系人信息")
                                widget.get("subnav").show(["contactsreturn"]).hide([ "save", "return","servicePoint"]);
                                widget.show([".J-contactsform"]).hide([".J-form", ".J-contactsgrid"]);
                            }
                        }, {
                            key: "delete",
                            icon: "icon-remove",
                            handler: function(index, data, rowEle) {
                                Dialog.confirm({
                                    content: "是否确认删除该条数据？",
                                    confirm: function() {
                                        pktemp.push(data.pkContacts);
                                        var contactsgriddata = widget.get("contactsgrid").getData();
                                        contactsgriddata.splice(index, 1);
                                        widget.get("contactsgrid").setData(contactsgriddata);
                                    },
                                    cancel: function() {
                                        Dialog.close;
                                    }
                                });
                            }
                        }]
                    }]
                }
            });
            this.set("contactsgrid", contactsgrid);

            var contactsform = new Form({
                parentNode: ".J-contactsform",
                saveaction: function() {
                    var data = widget.get("contactsfrom").getData();
                    if (data.idNumber.length > 0 && isIdCardNo(data.idNumber) == false) {
                        Dialog.confirm({
                            title: "身份证号填写格式错误",
                            content: "只能填写数字和英文"
                        })
                        return false;
                    }
                    if (isNaN(data.mobilePhone)) {
                        Dialog.confirm({
                            title: "移动电话格式填写错误",
                            content: "只能填写数字"
                        })
                        return false;
                    }
                    if (data.mobilePhone != "" && data.mobilePhone.length != 11) {
                        Dialog.confirm({
                            title: " 移动电话格式填写错误",
                            content: "有效号码是11位数字"
                        })
                        return false;
                    }
                    var carddata = widget.get("contactsgrid").getData();
                    if (data.index != "") {
                        carddata[data.index] = data;
                    } else {
                        carddata.push(data);
                    }
                    widget.get("contactsgrid").setData(carddata);
                    widget.get("subnav").setTitle("会员基本信息");
                    widget.get("subnav").hide([ "contactsreturn"]).show(["save", "return", "servicePoint"]);
                    widget.hide([".J-contactsform"]).show([".J-form", ".J-contactsgrid"]);
                },
                cancelaction: function() {
                    widget.get("subnav").setTitle("会员基本信息");
                    widget.get("subnav").hide([ "addressreturn", "interest"]).show(["save", "return", "servicePoint"]);
                    widget.hide([".J-contactsform"]).show([".J-form", ".J-contactsgrid"]);
                },
                model: {
                    id: "contacts",
                    layout: "2_1",
                    items: [{
                        name: "pkContacts",
                        type: "hidden",
                    }, {
                        name: "version",
                        defaultValue: "0",
                        type: "hidden"
                    }, {
                        name: "index",
                        type: "hidden"
                    }, {
                        name: "name",
                        label: "姓名",
                        validate: ["required"],
                        exValidate: function(value) {
                            if (value.length > 5) {
                                return "姓名限制5个字";
                            } else {
                                return true;
                            }
                        }
                    }, {
                        name: "sex",
                        label: "性别",
                        type: "radio",
                        list: [{
                            key: "Male",
                            value: "男"
                        }, {
                            key: "Female",
                            value: "女"
                        }],
                    }, {
                        name: "relation",
                        label: "与会员关系",
                        exValidate: function(value) {
                            if (value.length > 6) {
                                return "关系限制6个字";
                            } else {
                                return true;
                            }
                        }
                    }, {
                        name: "sosContact",
                        label: "是否紧急联系人",
                        type: "radio",
                        list: [{
                            key: true,
                            value: "是"
                        }, {
                            key: false,
                            value: "否"
                        }],
                    }, {
                        name: "mobilePhone",
                        label: "联系电话",
                        exValidate: function(value) {
                            if (value.length > 11) {
                                return "号码限制11位";
                            } else {
                                return true;
                            }
                        }
                    }, {
                        name: "work",
                        label: "工作单位"
                    }, {
                        name: "idType",
                        label: "证件类型",
                        type: "select",
                        options: enmu["com.eling.elcms.basedoc.model.IdType"],
                        defaultValue: "IdentityCard",
                        validate: ["required"]
                    }, {
                        name: "idNumber",
                        label: "身份证号",
                        exValidate: function(value) {
                            if (value.match(/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/) == false) {
                                return "身份证号格式错误";
                            } else {
                                return true;
                            }
                        }
                    }, {
                        name: "birthday",
                        label: "出生日期",
                        type: "date",
                    }, {
                        name: "age",
                        label: "年龄",
                        readonly: true,
                        disabled: true, 
                    }, {
                        name: "address",
                        label: "通讯地址"
                    }, {
                        name: "zipCode",
                        label: "邮编"
                    }]
                }
            });
            this.set("contactsfrom", contactsform);

        },
        

        afterInitComponent: function(params, widget) {
            /*for (var i = 0; i < activeUser.roles.length; i++) {
                if (activeUser.roles[i].pkRole == 33) {
                    isGovern = true;
                    break;
                }
            }
            if (isGovern) { //政府
                widget.loadOrganization(widget);
            } else {*/
//                aw.ajax({
//                    url: "api/servicepoint/operableservicepoints",
//                    dataType: "json",
//                    data: {},
//                    success: function(data) {
//                        widget.get("subnav").setData("servicePoint", data);
                        widget.setParams(widget);
                        widget.get("grid").refresh();
                        widget.get("contactsgrid").setTitle("联系人信息");
                        $(".J-form-meminformation-date-birthday").append(
                            "<label class='tranditional'><input type='checkbox' id='check' name='checkbox'>农历</label>"
                        );
//                    }
//                });
            /*}*/
        },
    });
    module.exports = member;
});
